package top.lileix.mybatis.generator.x.generator;

import java.io.IOException;

import top.lileix.mybatis.generator.x.domain.Table;
import top.lileix.mybatis.generator.x.domain.mapper.MapperXML;
import top.lileix.mybatis.generator.x.domain.mapper.MyBatisSQL;
import top.lileix.mybatis.generator.x.kit.FileKit;

/**
 * mapper文件生成器
 * 
 * @author lilei
 *
 */
public class MapperGenerator implements Generator {
    private String packageName;// 包名
    private String outputDir;// 放代码的路径
    private String domianPackPath;

    public MapperGenerator(String outputDir, String packageName, String domianPackPath) {
	super();
	this.packageName = packageName;
	this.outputDir = outputDir;
	this.domianPackPath = domianPackPath;
    }

    protected String packageTemplate = "package %s;%n%n";
    protected static String importTemplate = "import %s.%s;%n%n";
    protected static String classDefineTemplate = "/**%n" + " power by lileix.top %n %s" + " */%n"
	    + "public interface %s {%n%s}";

    @Override
    public String generatorStr(Table t) {
	StringBuilder sb = new StringBuilder();
	sb.append(String.format(packageTemplate, packageName));
	sb.append(String.format(importTemplate, domianPackPath, t.getModeName()));
	sb.append(
		String.format(classDefineTemplate, t.getRemark(), t.getModeName(), getMethods(t)));

	return sb.toString();
    }

    protected static String methodsTemplate = "\t%s %s (%s);%n%n";

    private String getMethods(Table t) {
	MapperXML xml = new MapperXML(t, domianPackPath);
	StringBuilder sb = new StringBuilder();
	for (MyBatisSQL s : xml.sqls) {
	    sb.append(String.format(methodsTemplate, s.javaReturnType, s.id, s.parameterType));
	}
	return sb.toString();
    }

    @Override
    public boolean generatorFile(Table t) throws IOException {
	FileKit.wirtToFile(outputDir, t.getModeName() + "Mapper.java", generatorStr(t), true);
	return true;
    }

}
